<template>
  <Row justify="center">
    <Col :span="8">
      <div class="step1Form">
        <Form :model="formState" ref="formRef" v-bind="formItemLayout">
          <FormItem
            label="应用"
            v-if="!redireactAppId"
            name="appId"
            :rules="[{ required: true, message: '请选择应用' }]"
          >
            <Select
              v-model:value="formState.appId"
              :options="appOpt"
              style="width: 260px"
              placeholder="请选择应用"
            ></Select
          ></FormItem>
          <FormItem label="应用" v-if="redireactAppId">{{ appName }} </FormItem>
          <InstanceRadioGroup ref="getPackage" @useFile="showFile" @getTenantType="ifShowPaymentType">
          </InstanceRadioGroup>
          <template v-if="formState.ifSupportFileSystem && architecture.value == '微服务'">
            <FormItem label="文件系统" v-if="false">
              <Select
                v-model:value="formState.fileSystemDto.fileSystemType"
                :options="fileTypeOpt"
                style="width: 260px"
                placeholder="请选择文件系统类型"
              ></Select
            ></FormItem>

            <FormItem label="挂载路径" v-if="false"
              ><Input
                v-model:value="formState.fileSystemDto.mountPath"
                style="width: 260px"
                placeholder="请输入挂载路径"
              ></Input
            ></FormItem>
          </template>
          <FormItem
            v-if="showStratege"
            label="管理面策略"
            name="deployStrategy"
            :rules="[{ required: true, message: '请选择管理面策略' }]"
          >
            <RadioGroup v-model:value="formState.deployStrategy" name="radioGroup">
              <Radio value="shared">共享</Radio>
              <Radio value="exclusive">独享</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem
            label="接收通知"
            name="isEnableNotification"
            :rules="[{ required: true, message: '请选择是否接收消息通知' }]"
            v-if="false"
          >
            <RadioGroup v-model:value="formState.isEnableNotification" name="isEnableNotification">
              <Radio :value="true">是</Radio>
              <Radio :value="false">否</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem
            label="通知方式"
            name="notificationType"
            v-if="formState.isEnableNotification"
            :rules="[{ required: true, message: '请选择通知方式' }]"
          >
            <RadioGroup v-model:value="formState.notificationType" name="radioGroup">
              <Radio value="sms">短信</Radio>
              <Radio value="email">邮件</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem
            v-if="formState.isEnableNotification && formState.notificationType == 'sms'"
            label="手机号"
            name="notificationTerminal"
            :rules="[
              {
                pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/,
                message: '请输入正确的手机号',
              },
              { required: true, message: '请输入手机号' },
            ]"
          >
            <Input
              v-model:value="formState.notificationTerminal"
              placeholder="请输入手机号"
              style="width: 260px"
            ></Input>
          </FormItem>
          <FormItem
            v-if="formState.isEnableNotification && formState.notificationType == 'email'"
            label="邮箱"
            name="notificationTerminal"
            :rules="[
              {
                type: 'email',
                message: '请输入正确的邮箱',
              },
              { required: true, message: '请输入邮箱' },
            ]"
          >
            <Input v-model:value="formState.notificationTerminal" placeholder="请输入邮箱" style="width: 260px"></Input>
          </FormItem>
          <template v-if="showPayment">
            <FormItem label="付费类型" name="paymentType" :rules="[{ required: true, message: '请选择付费类型' }]">
              <RadioGroup v-model:value="formState['paymentType']">
                <Radio value="prePaid">包周期</Radio>
                <Radio value="postPaid">按需付费</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem
              v-if="formState.paymentType == 'prePaid'"
              label="购买时长"
              name="duration"
              :rules="[{ required: true, message: '请选择购买时长' }]"
            >
              <InputNumber
                v-model:value="formState.duration"
                placeholder="请选择购买时长"
                :min="1"
                style="width: 130px"
              ></InputNumber>
              个月
            </FormItem>
          </template>
          <FormItem>
            <div class="btn-wrapper">
              <Button type="primary" @click="next">下一步</Button>
            </div>
          </FormItem>
        </Form>
      </div>
    </Col>
  </Row>
</template>
<script lang="ts" setup>
import {
  Button,
  message,
  Form,
  FormItem,
  RadioGroup,
  Radio,
  Select,
  Input,
  InputNumber,
  Col,
  Row,
} from 'ant-design-vue';
import InstanceRadioGroup from '/@/views/instance-purchase/components/InstanceRadioGroup.vue';
import { ref, watchEffect } from 'vue';
import { SaaSPurchaseInstanceParams } from '/@/api/instance-purchase/model/purchaseModel';
import { getAppSelectList } from '/@/api/system-mgmt/app-mgmt/app';
import { router } from '/@/router';
import { useUserStoreWithout } from '/@/store/modules/user';
import { getIfDeploy } from '/@/api/instance-purchase/purchase';

const userStore = useUserStoreWithout();
const userId = userStore.getUserInfo.userId;
const tenantCode = userStore.getUserInfo?.tenantCode as string;
const redireactAppId = router.currentRoute.value.query.appId;
const appName = ref();
const formState = ref({} as SaaSPurchaseInstanceParams);
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};

const showStratege = ref(false);
const getIfDeployment = async () => {
  formState.value.ifDeploy = await getIfDeploy(userId);
  showStratege.value = !formState.value.ifDeploy.isDeployConsole;
};
getIfDeployment();

const appOpt = ref([]);
const getSelectedAppName = () => {
  appOpt.value.forEach((item) => {
    if (item.value === formState.value.appId) {
      appName.value = item.label;
    }
  });
};
const getAppOptions = async () => {
  if (!redireactAppId) {
    appOpt.value = await getAppSelectList({ tenantCode });
    getSelectedAppName();
  } else {
    appOpt.value = await getAppSelectList({ tenantCode });
    formState.value.appId = redireactAppId;
    getSelectedAppName();
  }
};
getAppOptions();

const getPackage = ref(null);

watchEffect(() => {
  if (formState.value.appId) {
    getPackage.value.getPackageOpt(formState.value.appId, tenantCode);
    formState.value.ifSupportFileSystem = false;
  }
});
const showPayment = ref(false);
const ifShowPaymentType = (tenantType: number) => {
  if (tenantType !== 1) {
    showPayment.value = true;
  } else {
    showPayment.value = false;
  }
};
const fileTypeOpt = ref([
  { label: 'obs', value: 'obs' },
  { label: 'sfs', value: 'sfs' },
]);
const architecture = ref();
const showFile = () => {
  formState.value.ifSupportFileSystem = getPackage.value.selectedInstance.ifSupportFileSystem;
  architecture.value = getPackage.value.selectedInstance.architecture;
};

const emit = defineEmits(['viewStep1']);
const formRef = ref();
const next = () => {
  if (!getPackage.value.selectedInstance) {
    message.error('请选择套餐规格！');
  } else {
    formState.value.packageId = getPackage.value.selectedInstance.id;
    formState.value.type = getPackage.value.selectedInstance.type;
    formState.value.isSupportLicenseMgmt = getPackage.value.selectedInstance.ifSupportLicenseMgmt;
    formState.value.isIntegrateThirdApp = getPackage.value.selectedInstance.ifIntegrateThirdApp;
    formState.value.tenantCode = tenantCode;
    formState.value.packageType = getPackage.value.selectedInstance.packageType;
    formState.value.dbMultiTenantMode = getPackage.value.selectedInstance.dbMultiTenantMode;
    formState.value.appMultiTenantMode = getPackage.value.selectedInstance.appMultiTenantMode;
    formState.value.tenantType = getPackage.value.selectedInstance.tenantType;
    getSelectedAppName();
    if (formState.value.duration) {
      let month = formState.value.duration;

      // 提前增加8小时防止丢失时区问题
      let today = new Date(+new Date() + 8 * 3600 * 1000);
      let expirationTime = today.setMonth(today.getMonth() + month);
      formState.value.expireTime = new Date(expirationTime).toISOString();
    }
    if (formState.value.ifDeploy.isDeployConsole) {
      delete formState.value.deployStrategy;
    }
    formRef.value.validate().then(() => {
      if (!formState.value.duration && formState.value.tenantType == 1) {
        formState.value.paymentType = 'prePaid';
        formState.value.expireTime = getPackage.value.selectedInstance.expireTime;
      }
      emit('viewStep1', formState.value);
    });
  }
};

defineExpose({ appName });
</script>
<style lang="less" scoped>
.btn-wrapper {
  float: right;
}
.step1Form {
  min-width: 50%;
}
</style>
